package com.lu.dog.dbrowser.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lu.adog.base.BaseActivity;
import com.lu.adog.base.BaseConfig;
import com.lu.adog.util.Logg;
import com.lu.dog.dbrowser.R;
import com.lu.dog.dbrowser.bean.IconInfo;
import com.lu.dog.dbrowser.bean.SearchInfo;
import com.lu.dog.dbrowser.db.DBrowserDbHelper;
import com.lu.dog.dbrowser.ui.adapter.ItemIconAdapter;
import com.lu.dog.dbrowser.ui.adapter.SearchInfoAdapter;
import com.lu.dog.util.AppUtil;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity {


    private long clickBackTime;
    private SearchInfoAdapter searchAdapter;
    private Toolbar toolbar;
    private ImageView ivSearch;
    private EditText etSearch;
    private FrameLayout flScanCancel;
    private TextView tvCancel;
    private RecyclerView rvItemIcon;
    private ListView lvSearch;
    private ImageView ivScan;
    private ItemIconAdapter itemIconAdapter;
    private TextView tvBottom;
    private View layoutBottom;
    private ImageView ivRollBottom;

//    private void initData() {
//        long time = System.currentTimeMillis();
//        List<IconInfo> iconInfos = new ArrayList<>();

//        String httpIp4 = "http://"+NetAddressUitl.getIPAddress(this);
//        Logg.w(">>>",httpIp4+"   方法对比   "+NetAddressUitl.getHostIp());
//
//        iconInfos.add(new IconInfo(4, httpIp4+":3000", "3000", null, null, time, time));
//        iconInfos.add(new IconInfo(5, httpIp4+":3100", "3100", null, null, time, time));
//        iconInfos.add(new IconInfo(6, httpIp4+":8080", "8080", null, null, time, time));
//        DBrowserDbHelper.getInstance(this).updateIconInfo(iconInfos);

//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        initData();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        assignViews();
    }

    private void assignViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ivSearch = (ImageView) findViewById(R.id.ivSearch);
        etSearch = (EditText) findViewById(R.id.etSearch);
        flScanCancel = (FrameLayout) findViewById(R.id.flScanCancel);
        tvCancel = (TextView) findViewById(R.id.tvCancel);
        rvItemIcon = (RecyclerView) findViewById(R.id.rvItemIcon);
        lvSearch = (ListView) findViewById(R.id.lvSearch);
        ivScan = (ImageView) findViewById(R.id.ivScan);
        layoutBottom = findViewById(R.id.layoutBottom);
        tvBottom = (TextView) findViewById(R.id.tvBottom);
        ivRollBottom = (ImageView) findViewById(R.id.ivRollBottom);

        itemIconAdapter = new ItemIconAdapter(this, R.layout.item_itemicon, new ArrayList<ItemIconAdapter.ItemData>());
        rvItemIcon.setAdapter(itemIconAdapter);

        GridLayoutManager layoutManager = new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        rvItemIcon.setLayoutManager(layoutManager);

        searchAdapter = new SearchInfoAdapter(this, R.layout.item_search, new ArrayList<SearchInfo>());
        lvSearch.setAdapter(searchAdapter);

        ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        etSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSearchListAction();
                if (etSearch.getText().toString().length() == 0) {
                    hideBottomBar();
                } else {
                    showBottomBar(BaseConfig.TAG_VISIT);
                }

            }
        });


        etSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {

                } else {
                    hideSearchListAction();
                }

            }
        });

        flScanCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ivScan.getVisibility() == View.VISIBLE) {
                    visityScannerActitity();

                } else {
                    //取消
                    hideSearchListAction();
                }
            }
        });


        tvBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bottomTag == BaseConfig.TAG_VISIT) {//前往
                    visityWebActivity();
                } else {//textView为完成
                    hideAllActionView();
                }

            }
        });

        ivRollBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideBottomBar();
                itemIconAdapter.hideDeleteMoreView();
            }
        });

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etSearch.getText().toString().length() == 0) {
                    hideBottomBar();
                } else {
                    showBottomBar(BaseConfig.TAG_VISIT);
                }
            }
        });
    }

    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && this.getCurrentFocus() != null) {
            if (this.getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    private void hideAllActionView() {
        hideSearchListAction();
        hideBottomBar();

        itemIconAdapter.hideDeleteMoreView();

        hideBottomBar();
        hideSearchListAction();

    }

    private int bottomTag = BaseConfig.TAG_VISIT;

    public void showBottomBar(int tag) {
        if (tag == BaseConfig.TAG_VISIT) {
            tvBottom.setText("前往");
        } else {
            tvBottom.setText("完成");
        }
        if (layoutBottom.getVisibility() != View.VISIBLE) {
            layoutBottom.setVisibility(View.VISIBLE);
        }
        bottomTag = tag;
    }

    public void hideBottomBar() {
        layoutBottom.setVisibility(View.GONE);
    }

    private void visityScannerActitity() {

        requirePermisson(1001, new String[]{Manifest.permission.CAMERA}, new PermissonCallback() {
            @Override
            public void callBack(boolean hasPer, String[] permissions, int[] grantResults) {
                Logg.w(">>>权限申请", hasPer);
                if (hasPer) {
                    //二维码扫描
                    Intent intent = new Intent(MainActivity.this, SimpleQRCodeActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(MainActivity.this, "需要摄像头权限才能够扫码", Toast.LENGTH_SHORT).show();
                }
            }
        });


//        int flag1 = PermissionChecker.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA);
//        int flag2 = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA);
//        int flag4 = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA);
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
//            int flag3 = checkSelfPermission(Manifest.permission.CAMERA);
//            Logg.w("权限>>>", flag1 + "   " + flag2 + "   " + flag3 + "  " + flag4);
//        }

    }

    public void showSearchListAction() {
        if (lvSearch.getVisibility() != View.VISIBLE) {

            tvCancel.setVisibility(View.VISIBLE);
            ivScan.setVisibility(View.GONE);

            lvSearch.setVisibility(View.VISIBLE);
            searchAdapter.getDatas().clear();
            searchAdapter.getDatas().addAll(DBrowserDbHelper.getInstance(this).selectAllSearchInfo());
            searchAdapter.notifyDataSetChanged();


        }
    }

    public void hideSearchListAction() {
        if (lvSearch.getVisibility() != View.GONE) {
            lvSearch.setVisibility(View.GONE);

            tvCancel.setVisibility(View.GONE);
            ivScan.setVisibility(View.VISIBLE);
        }
        hideKeyboard();
    }

    public void putSearchText(String text) {
        etSearch.setText(text);
    }

    private void visityWebActivity() {
        String url = etSearch.getText().toString().trim();
        if (TextUtils.isEmpty(url)) {
            return;
        }

        hideAllActionView();

        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra(BaseConfig.KEY_URL, url);
        startActivity(intent);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (lvSearch.getVisibility() == View.VISIBLE) {
                hideSearchListAction();
            } else {
                quickClickExit();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {

        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 1, Menu.NONE, "查看日志");
        menu.add(0, 2, Menu.NONE, "关于");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 1:
                Intent intent = new Intent(this, LogActivity.class);
                startActivity(intent);
                break;
            case 2:
                String text = "v"+AppUtil.getAppVersionName(this);
                Toast.makeText(this,text,Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void quickClickExit() {
        if ((System.currentTimeMillis() - clickBackTime) > 1500) {
            Toast.makeText(getApplicationContext(), "再按一次退出", Toast.LENGTH_SHORT).show();
            clickBackTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

    private final static int ZXING_CAMERA_PERMISSION = 200;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DBrowserDbHelper.getInstance(this).close();
    }
}
